package com.xiaohai.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaohai.common.R;
import com.xiaohai.projo.Major;
import com.xiaohai.projo.Student;
import com.xiaohai.projo.Teacher;
import com.xiaohai.service.MajorService;
import com.xiaohai.service.StudentService;
import com.xiaohai.service.TeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xiaohai
 * @since 2024-02-24
 */

@RestController
@Slf4j
@RequestMapping("/major")
public class MajorController {
    @Autowired
    private MajorService majorService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private StudentService studentService;

    @GetMapping("/list")
    public R<Page<Major>> list(Integer currentPage, Integer pageSize, String name) {

        Page<Major> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<Major> majorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        majorLambdaQueryWrapper.like(name != null, Major::getName, name);
        Page<Major> list = majorService.page(page, majorLambdaQueryWrapper);
        return R.success(list, "获取数据成功");
    }

    @DeleteMapping
    public R deleteById(Integer id) {
        Student student = studentService.getById(id);
        Teacher teacher = teacherService.getById(id);
        if (Objects.isNull(student) && Objects.isNull(teacher)) {
            majorService.removeById(id);
            return R.success(200, "删除成功");
        }
        return R.error("删除失败,该专业有学生存在或专业教师正在授课", 201);
    }

    @PostMapping
    public R<Objects> add(@RequestBody Major major) {
        log.info("major:{}", major);

        Integer id = major.getId();

        if (id!=null) {// 修改
            boolean update = majorService.myUpdate(major);
            if (update) {
                return R.success(null, "修改成功");
            }
            return R.error("修改失败", 201);
        } else {// 新增
            log.info("1111111");
            boolean b = majorService.mySave(major);
            if (!b) {

                return R.error("新增失败", 201);
            }
            return R.success(null, "新增成功");
        }
    }

    @GetMapping
    public R<Major> detail(String id) {
        Major major = majorService.detail(id);
        if (Objects.isNull(major)) {
            return R.error("获取详情失败", 201);
        }
        return R.success(major, "获取详情成功");
    }

}
